<template>
  <div>
    <el-dialog :title="title"
               :visible.sync="visible"
               v-loading="loading"
               :before-close="modalClose"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="80%">
      <el-form :model="formModel"
               label-position="right"
               ref="formRef"
               label-width="150px"
               :rules='formRules'>
        <el-form-item label="所属医院：">
          <el-select v-model="formModel.hospitalId"
                     clearable
                     class="w-200"
                     placeholder="请选择所属医院"
                     :disabled="interpretationConfigObj ? true : false"
                     @change="changeHospital">
            <el-option v-for="item in hospitalList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医生配置：">
          <span style="color:#f56c6c"
                v-if="isAddBtn">根据医院查询医生配置</span>
          <template v-if="!isAddBtn">
            <el-radio-group v-model="formModel.serviceType"
                            @change="changeRadio">
              <el-radio-button v-for="item in listData"
                               :label="item.value"
                               :key="item.value">{{item.label}}
              </el-radio-button>
            </el-radio-group>
          </template>
        </el-form-item>

        <el-button type="primary"
                   @click="handleOption('add', null)"
                   :disabled="isAddBtn">新 增</el-button>
        <element-table class="mt-20"
                       v-loading="loadingTable"
                       :columns="columns"
                       :data="tableData"
                       pager
                       :pageTotal="pageTotal"
                       :pageIndex="pageIndex"
                       :pageSize="pageSize"
                       @handleChangePage="handleChangePage">
          <template v-slot:option="{row}">
            <el-button type="primary"
                       @click="handleOption('edit', row)">编 辑</el-button>
            <el-button type="danger"
                       @click="handleOption('del', row)">删 除</el-button>
          </template>
        </element-table>

      </el-form>
      <!-- 新增、编辑医生 -->
      <el-dialog width="30%"
                 :title="childTitle"
                 :visible.sync="innerVisible"
                 append-to-body>
        <el-form :model="formData"
                 label-position="right"
                 ref="formDataRef"
                 label-width="150px"
                 :rules='formDataRules'>
          <el-form-item label="医生账号："
                        prop="doctorId">
            <el-input placeholder="请输入医生账号"
                      :disabled="isRead"
                      v-model="formData.doctorId"
                      @change="handleInput"
                      class="w-200"></el-input>

          </el-form-item>
          <el-form-item label="姓名：">
            <el-input placeholder="根据医生账号查找医生姓名"
                      :disabled="true"
                      v-model="formData.doctorName"
                      class="w-200"></el-input>
          </el-form-item>
          <el-form-item label="所在科室：">
            <el-input placeholder="根据医生账号查找所在科室"
                      :disabled="true"
                      v-model="formData.departmentName"
                      class="w-200"></el-input>
          </el-form-item>
          <el-form-item label="解读费用："
                        prop="price">
            <el-input-number placeholder="请输入解读费用"
                             :precision="2"
                             :min="0"
                             :controls="false"
                             v-model="formData.price"
                             class="w-200"></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button @click="innerVisible = false">取 消</el-button>
            <el-button type="primary"
                       :disabled="isSaveBtn"
                       @click="onSubmit(saveType)">保 存</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
  import elementTable from '@/base/ElementTable'
  export default {
    name: '', // 解读配置
    props: {
      interpretationConfigObj: {
        type: Object,
        default: {}
      },
      visible: {
        type: Boolean,
        default: false
      },
      getList: {
        type: Function,
        default: null
      }
    },
    data () {
      return {
        title: '新 增',
        loading: false,
        loadingTable: false,
        loadingInput: false,
        isAddBtn: true,
        isSaveBtn: true,
        innerVisible: false,
        formModel: {
          serviceType: 3
        },
        formRules: {},
        hospitalList: [], // 所有医院列表
        selectHospitalId: '', // 所属医院Id
        currentIndex: 0, // 医生配置 type
        listData: [],
        columns: [
          {
            label: '医生姓名',
            prop: 'doctorName'
          },
          {
            label: '账号',
            prop: 'loginName',
            showToolTip: true
          },
          {
            label: '职级',
            prop: 'departmentName',
            showToolTip: true
          },
          {
            label: '解读费用（元）',
            prop: 'price',
            showToolTip: true
          },
          {
            label: '操作',
            prop: 'option',
            width: 250,
            isSlot: true
          }
        ],
        tableData: [],
        pageTotal: 0,
        pageIndex: 1,
        pageSize: 10,
        childTitle: '',
        formData: {},
        formDataRules: {
          doctorId: [
            { required: true, message: '请输入医生账号', trigger: 'blur' },
          ],
          doctorName: [
            { required: true, message: '根据医生账号查找医生姓名', trigger: 'blur' },
          ],
          departmentName: [
            { required: true, message: '根据医生账号查找所在科室', trigger: 'blur' },
          ],
          price: [
            { required: true, message: '请输入解读费用', trigger: 'blur' },
          ]
        },
        saveType: '',
        isRead: false,
        servId: '',
        currDoctorId: '',
      }
    },
    methods: {
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },
      // 查询所有医院
      async getAllHospital () {
        const { data: res } = await this.post(this.api.hospitalECG.selectRemoteHospitalByName, {
          remoteType: null,
          hospitalName: '',
          pageIndex: 0,
          pageSize: 100
        })
        if (res.code === '200') {
          this.hospitalList = res.object
        }
      },
      // 选择医院
      changeHospital (val) {
        this.selectHospitalId = val
        this.isAddBtn = this.selectHospitalId ? false : true
        this.getTitle() // 查询该医院开通的业务
      },
      // 查询该医院开通的业务
      async getTitle () {
        const { data: res } = await this.post(this.api.hospitalECG.selectRemoteReadById, {
          id: this.selectHospitalId
        })
        if (res.code === '200') {
          let newArray = res.object.map(item => {
            if (item === 3) {
              return { value: 3, label: '胎心解读配置' }
            }
            if (item === 4) {
              return { value: 4, label: '心电解读配置' }
            }
            if (item === 5) {
              return { value: 5, label: '四高解读配置' }
            }
          })
          this.listData = newArray

          this.changeRadio(this.listData[0].value) // 每次切换医院，默认选中该医院下开通的第一项业务
          this.formModel.serviceType = this.listData[0].value
        }
      },

      // 选择医生配置
      changeRadio (val) {
        this.currentIndex = val
        this.selectReadDoctorList()
      },
      // 查询医院下的胎心解读医生
      async selectReadDoctorList () {
        this.loading = true
        const { data: res } = await this.post(this.api.hospitalECG.getRemoteTypeList, {
          pageIndex: this.pageIndex - 1,
          pageSize: this.pageSize,
          remoteType: this.currentIndex, // 远程类型 3 胎心 4 心电 5 四高
          id: this.selectHospitalId
        })
        if (res.code === '200') {
          this.loading = false
          this.tableData = res.object
          this.pageTotal = res.totalNum
        }
      },
      // 分页
      handleChangePage (page) {
        this.pageIndex = page
        this.selectReadDoctorList();
      },
      // 操作
      handleOption (op, row) {
        switch (op) {
          case 'add':
            this.innerVisible = true
            this.childTitle = '新增医生'
            this.saveType = 'add'
            this.isRead = false
            if (this.$refs.formDataRef) {
              this.$refs.formDataRef.resetFields()
            }
            break;
          case 'edit':
            this.innerVisible = true
            this.childTitle = '编辑医生'
            this.saveType = 'edit'
            this.isRead = true
            this.isSaveBtn = false
            this.servId = row.servId
            this.formData.doctorId = row.loginName
            this.formData.departmentName = row.departmentName
            this.formData.doctorName = row.doctorName
            this.formData.price = row.price

            break;
          case 'del':
            this.$confirm('确认删除？')
              .then(async _ => {
                const { data: res } = await this.post(this.api.fourHigh.delReadDoctor, {
                  servId: row.servId,
                  remoteType: this.currentIndex,
                  hospitalId: this.selectHospitalId
                })
                if (res.code === '200') {
                  this.$message.success('删除成功!')
                  this.selectReadDoctorList()
                } else {
                  this.$message.error(res.message)
                }
              })
              .catch(_ => { });
            break;
        }
      },


      // 医生账号精准匹配
      async handleInput (query) {
        this.loadingInput = true
        this.doctorId = Number(query)
        const { data: response } = await this.post(this.api.fetaHeart.getDoctorInfoByLoginName, {
          loginName: query,
          hospitalId: this.selectHospitalId,
        })
        if (response.code === '200') {
          this.loadingInput = false
          this.isSaveBtn = false
          let resData = response.object
          this.currDoctorId = resData.doctorId
          this.formData.doctorName = resData.doctorName
          this.formData.departmentName = resData.departmentName
        } else {
          if (this.$refs.formDataRef) {
            this.$refs.formDataRef.resetFields()
          }
        }
      },
      onSubmit (saveType) {
        switch (saveType) {
          case 'add':
            this.$refs.formDataRef.validate(async (valid) => {
              if (valid) {
                const { data: res } = await this.post(this.api.hospitalECG.addReadDoctor, {
                  doctorId: this.currDoctorId,
                  price: this.formData.price,
                  hospitalId: this.selectHospitalId,
                  remoteType: this.currentIndex,
                })
                if (res.code === '200') {
                  this.$message.success('新增医生成功!')
                  this.innerVisible = false
                  this.selectReadDoctorList()
                } else {
                  this.$message.error(res.message)
                }
              }
            })
            break;
          case 'edit':
            this.$refs.formDataRef.validate(async (valid) => {
              if (valid) {
                const { data: result } = await this.post(this.api.fetaHeart.updateReadDoctorPrice, {
                  servId: this.servId,
                  price: this.formData.price
                })
                if (result.code === '200') {
                  this.$message.success('编辑医生成功!')
                  this.innerVisible = false
                  this.selectReadDoctorList()
                } else {
                  this.$message.error(result.message)
                }
              }
            })
            break;
        }
      },
    },
    created () {
      if (this.interpretationConfigObj) {
        this.selectHospitalId = this.interpretationConfigObj.hospitalId
        this.formModel.hospitalId = this.interpretationConfigObj.hospitalId
        this.changeHospital(this.selectHospitalId)
        this.title = '编 辑'
      } else {
        this.title = '新 增'
      }
      this.getAllHospital() // 查询所有医院
    },
    components: {
      'element-table': elementTable
    }
  }
</script>
<style scoped lang="scss">
</style>